# coding:UTF-8

import numpy as np
import svm
import sys


def load_data_libsvm(data_file):
    '''导入训练数据
    input:  data_file(string):训练数据所在文件
    output: data(mat):训练样本的特征
            label(mat):训练样本的标签
    '''
    data = []
    label = []
    f = open(data_file)

    for line in f.readlines():
        lines = line.strip().split(' ')
        length = len(lines)
        # 提取得出label
        label.append(float(lines[length - 1]))

        # 提取出特征，并将其放入到矩阵中
        tmp = []

        for i in range(0, length - 1):
            tmp.append(float(lines[i]))
        data.append(tmp)

    f.close()
    return np.mat(data), np.mat(label).T


if __name__ == "__main__":
    file_name = "201202_003004_100004_train.txt"
    model = "201202_003004_100004_model"
    # 1、导入训练数据
    dataSet, labels = load_data_libsvm(file_name)
    # 2、训练SVM模型
    C = 0.6
    toler = 0.001
    maxIter = 500
    svm_model = svm.SVM_training(dataSet, labels, C, toler, maxIter)
    # 3、计算训练的准确性
    accuracy = svm.cal_accuracy(svm_model, dataSet, labels)
    # 4、保存最终的SVM模型
    svm.save_svm_model(svm_model, model)
